import subprocess
import csv
import time


def get_cpu_usage():
    # 使用adb shell top命令获取CPU使用情况
    result = subprocess.check_output(['adb', 'shell', 'top', '-n', '1']).decode()
    # 解析结果以找到CPU使用率
    for line in result.splitlines():
        if 'CPU usage' in line:
            return line.split('%')[0].split(':')[1].strip()


def get_memory_usage():
    # 使用adb shell cat命令获取内存使用情况
    result = subprocess.check_output(['adb', 'shell', 'cat', '/proc/meminfo']).decode()
    # 解析结果以找到总内存和可用内存
    mem_info = {}
    for line in result.splitlines():
        key, value = line.split(':')
        mem_info[key] = int(value.strip().split()[0]) * 1024  # 将值转换为字节
    total_memory = mem_info['MemTotal']
    available_memory = mem_info['MemAvailable']
    used_memory = total_memory - available_memory
    return used_memory, total_memory


# 打印CPU和内存使用情况
print(f"CPU Usage: {get_cpu_usage()}%")
print(f"Memory Usage: {get_memory_usage()[0]} bytes")

# 获取CPU信息
cpu_process = subprocess.Popen(['adb', 'shell', 'dumpsys', 'cpuinfo'], stdout=subprocess.PIPE)
print(cpu_process)
grep_process = subprocess.Popen(['grep', 'CPU'], stdin=cpu_process.stdout, stdout=subprocess.PIPE)
cpu_info = grep_process.communicate()[0].decode('utf-8')
print(cpu_info)
cpu_data = cpu_info.split()[1:]
print(cpu_data)

# 获取内存信息
mem_process = subprocess.Popen(['adb', 'shell', 'dumpsys', 'meminfo'], stdout=subprocess.PIPE)
grep_process = subprocess.Popen(['grep', 'TOTAL'], stdin=cpu_process.stdout, stdout=subprocess.PIPE)
mem_info = grep_process.communicate()[0].decode('utf-8')
print(mem_info)  # todo 还需要调整
mem_data = mem_info.split()[1:]

# 将信息保存到CSV文件中
with open('/Users/admin/Desktop/翻译/pica_ios/3.0.1/3.0.1/cpu_memory.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Time', 'CPU Usage', 'Memory Usage'])
    for i in range(min(len(cpu_data), len(mem_data))):
        current_time = time.ctime()
        cpu_usage = cpu_data[i].split()[0] if cpu_data else ''
        memory_usage = mem_data[i].split()[0] if mem_data else ''
        writer.writerow([current_time, cpu_usage, memory_usage])
